import 'package:flutter/material.dart';
import 'package:video_player/video_player.dart';
import 'dart:async';

class VideoPlayerWidget extends StatefulWidget {
  final String videoUrl;
  final String coverImage;
  final bool isPlaying;
  final VoidCallback? onTap;

  const VideoPlayerWidget({
    super.key,
    required this.videoUrl,
    required this.coverImage,
    this.isPlaying = false,
    this.onTap,
  });

  @override
  State<VideoPlayerWidget> createState() => _VideoPlayerWidgetState();
}

class _VideoPlayerWidgetState extends State<VideoPlayerWidget> with WidgetsBindingObserver {
  VideoPlayerController? _controller;
  bool _isInitialized = false;
  bool _hasError = false;
  String _errorMessage = '';
  bool _showPlayIcon = false;
  int _retryCount = 0;
  final int _maxRetries = 1;
  Timer? _initTimer;
  Timer? _progressTimer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    // 延迟初始化，避免所有视频同时初始化
    Future.delayed(const Duration(milliseconds: 100), () {
      if (mounted) {
        _initializeVideo();
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    
    if (_controller == null || !_isInitialized) return;
    
    if (state == AppLifecycleState.paused) {
      _controller?.pause();
    } else if (state == AppLifecycleState.resumed && widget.isPlaying) {
      _controller?.play();
    }
  }

  void _initializeVideo() {
    // ⚡ 关键优化：只有当前页面正在播放时才初始化
    if (!widget.isPlaying) {
      debugPrint('⏸️ 非当前页，跳过初始化: ${widget.videoUrl}');
      return;
    }
    
    setState(() {
      _hasError = false;
      _errorMessage = '';
    });

    try {
      debugPrint('🎬 初始化视频: ${widget.videoUrl}');
      
      _controller = VideoPlayerController.networkUrl(
        Uri.parse(widget.videoUrl),
        httpHeaders: {
          'User-Agent': 'Mozilla/5.0 (Linux; Android 10) AppleWebKit/537.36',
        },
        videoPlayerOptions: VideoPlayerOptions(
          mixWithOthers: false, // 不与其他音频混合
          allowBackgroundPlayback: false, // 不允许后台播放
        ),
      );

      _initTimer = Timer(const Duration(seconds: 15), () {
        if (!_isInitialized && mounted) {
          debugPrint('⏰ 视频加载超时');
          _handleError('加载超时');
        }
      });

      _controller!.initialize().then((_) {
        _initTimer?.cancel();
        if (mounted) {
          debugPrint('✅ 视频初始化成功');
          setState(() {
            _isInitialized = true;
            _retryCount = 0;
          });
          
          _controller!.setLooping(true);
          
          if (widget.isPlaying) {
            _controller!.play();
          }
          
          _startProgressTimer();
        }
      }).catchError((error) {
        _initTimer?.cancel();
        debugPrint('❌ 视频初始化失败: $error');
        _handleError('加载失败');
      });

    } catch (e) {
      debugPrint('❌ 创建控制器失败: $e');
      _handleError('初始化失败');
    }
  }

  void _startProgressTimer() {
    _progressTimer?.cancel();
    _progressTimer = Timer.periodic(const Duration(milliseconds: 500), (timer) {
      if (mounted && _controller != null) {
        setState(() {});
      }
    });
  }

  void _handleError(String message) {
    if (!mounted) return;
    
    setState(() {
      _hasError = true;
      _errorMessage = message;
    });

    if (_retryCount < _maxRetries) {
      _retryCount++;
      debugPrint('🔄 自动重试 ($_retryCount/$_maxRetries)...');
      Future.delayed(Duration(seconds: _retryCount * 2), () {
        if (mounted) {
          _disposeController();
          _initializeVideo();
        }
      });
    } else {
      debugPrint('⛔ 达到最大重试次数');
    }
  }

  void _disposeController() {
    _initTimer?.cancel();
    _progressTimer?.cancel();
    _controller?.pause();
    _controller?.dispose();
    _controller = null;
    _isInitialized = false;
  }

  void _retryLoad() {
    _retryCount = 0;
    _disposeController();
    _initializeVideo();
  }

  @override
  void didUpdateWidget(VideoPlayerWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // ⚡ 关键优化：页面切换时的视频控制
    if (widget.isPlaying != oldWidget.isPlaying) {
      if (widget.isPlaying) {
        // 切换到当前页
        if (_controller == null && !_isInitialized) {
          // 首次播放，初始化视频
          debugPrint('🎬 首次播放，初始化视频');
          _initializeVideo();
        } else if (_controller != null && !_controller!.value.isPlaying) {
          // 已初始化，开始播放
          _controller!.play();
        }
      } else {
        // 切换离开当前页，暂停视频
        if (_controller != null && _controller!.value.isPlaying) {
          debugPrint('⏸️ 切换页面，暂停视频');
          _controller!.pause();
        }
      }
    }
  }

  void _togglePlayPause() {
    if (_controller == null || !_isInitialized) {
      widget.onTap?.call();
      return;
    }

    setState(() {
      if (_controller!.value.isPlaying) {
        _controller!.pause();
        _showPlayIcon = true;
      } else {
        _controller!.play();
        _showPlayIcon = false;
      }
    });

    if (_showPlayIcon) {
      Future.delayed(const Duration(milliseconds: 500), () {
        if (mounted) setState(() => _showPlayIcon = false);
      });
    }

    widget.onTap?.call();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: _hasError ? _retryLoad : _togglePlayPause,
      child: Container(
        color: Colors.black,
        child: Stack(
          fit: StackFit.expand,
          children: [
            // 视频播放器或封面图
            if (_isInitialized && _controller != null)
              Center(
                child: AspectRatio(
                  aspectRatio: _controller!.value.aspectRatio,
                  child: VideoPlayer(_controller!),
                ),
              )
            else
              // 封面图（加载中）
              Image.asset(
                widget.coverImage,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.black,
                    child: const Center(
                      child: Icon(
                        Icons.broken_image,
                        color: Colors.white54,
                        size: 80,
                      ),
                    ),
                  );
                },
              ),

            // 错误提示
            if (_hasError)
              Container(
                color: Colors.black87,
                child: Center(
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      const Icon(
                        Icons.error_outline,
                        color: Colors.white,
                        size: 60,
                      ),
                      const SizedBox(height: 16),
                      Padding(
                        padding: const EdgeInsets.symmetric(horizontal: 32),
                        child: Text(
                          _errorMessage,
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 14,
                          ),
                          textAlign: TextAlign.center,
                        ),
                      ),
                      const SizedBox(height: 20),
                      ElevatedButton.icon(
                        onPressed: _retryLoad,
                        icon: const Icon(Icons.refresh),
                        label: const Text('点击重试'),
                        style: ElevatedButton.styleFrom(
                          backgroundColor: Colors.white,
                          foregroundColor: Colors.black,
                        ),
                      ),
                    ],
                  ),
                ),
              )
            // 加载指示器
            else if (!_isInitialized)
              Container(
                color: Colors.black.withValues(alpha: 0.54),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    const CircularProgressIndicator(
                      color: Colors.white,
                    ),
                    const SizedBox(height: 16),
                    Text(
                      _retryCount > 0 ? '重试中... ($_retryCount/$_maxRetries)' : '加载中...',
                      style: const TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                      ),
                    ),
                  ],
                ),
              ),

            // 播放/暂停按钮 - 美化版
            if (_isInitialized && !_hasError)
              Center(
                child: AnimatedOpacity(
                  opacity: (_showPlayIcon || (_controller != null && !_controller!.value.isPlaying)) ? 1.0 : 0.0,
                  duration: const Duration(milliseconds: 300),
                  child: Container(
                    width: 85,
                    height: 85,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      gradient: LinearGradient(
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                        colors: [
                          Colors.white.withValues(alpha: 0.3),
                          Colors.white.withValues(alpha: 0.15),
                        ],
                      ),
                      boxShadow: [
                        BoxShadow(
                          color: Colors.black.withValues(alpha: 0.3),
                          blurRadius: 20,
                          spreadRadius: 2,
                        ),
                      ],
                    ),
                    child: Container(
                      margin: const EdgeInsets.all(3),
                      decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        gradient: LinearGradient(
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                          colors: [
                            Colors.white.withValues(alpha: 0.25),
                            Colors.white.withValues(alpha: 0.1),
                          ],
                        ),
                      ),
                      child: Icon(
                        (_controller != null && _controller!.value.isPlaying && !_showPlayIcon) 
                            ? Icons.pause_rounded 
                            : Icons.play_arrow_rounded,
                        color: Colors.white,
                        size: 45,
                        shadows: const [
                          Shadow(
                            color: Colors.black45,
                            blurRadius: 10,
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ),

            // 视频进度条
            if (_isInitialized && !_hasError && _controller != null)
              Positioned(
                bottom: 80,
                left: 12,
                right: 12,
                child: Column(
                  children: [
                    VideoProgressIndicator(
                      _controller!,
                      allowScrubbing: true,
                      colors: VideoProgressColors(
                        playedColor: Colors.white,
                        bufferedColor: Colors.white.withValues(alpha: 0.3),
                        backgroundColor: Colors.white.withValues(alpha: 0.1),
                      ),
                      padding: const EdgeInsets.symmetric(vertical: 4),
                    ),
                    const SizedBox(height: 4),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          _formatDuration(_controller!.value.position),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            shadows: [
                              Shadow(color: Colors.black54, blurRadius: 3),
                            ],
                          ),
                        ),
                        Text(
                          _formatDuration(_controller!.value.duration),
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 12,
                            shadows: [
                              Shadow(color: Colors.black54, blurRadius: 3),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _disposeController();
    super.dispose();
  }
}
